package com.woniu.job;

import com.woniu.entity.Equipment;
import com.woniu.mapper.EquipmentMapper;
import com.woniu.websocket.NotificationWebSocket;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;

@Slf4j
//@Component
public class EquipmentMaintenanceJob implements Job {
    @Resource
    private EquipmentMapper equipmentMapper;

    @Override
    @Transactional
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("【设备维护任务】开始执行...");

        LocalDate today = LocalDate.now();
        List<Equipment> equipmentList = equipmentMapper.selectByNextMaintenanceDateEquipment(today);

        for (Equipment equipment : equipmentList) {
            String message = String.format("【设备维护提醒】设备 %s (%s) 今日需维护，购买日期：%s",
                    equipment.getEquipName(), equipment.getEquipCode(), equipment.getPurchaseDate());

            // 直接调用静态方法发送通知
            NotificationWebSocket.sendToRole("resource_manager", message);

            // 更新设备状态
            equipment.setMaintenanceStatus(1);
            equipmentMapper.updateByPrimaryKeySelective(equipment);

            log.info("【设备维护任务】设备 {} 提醒已发送", equipment.getId());
        }

        log.info("【设备维护任务】执行完成，共提醒 {} 台设备", equipmentList.size());
    }

    }
